import Taro, {Component} from '@tarojs/taro'
import {View, Text, Image,Button , Picker} from '@tarojs/components'

import {
  AtInput,
  AtNoticebar,
  AtTextarea,
  AtRadio
} from 'taro-ui'

import CustomRadio from '../../component/CustomRadio/customRadio'

import './shopInfoPost.scss'

import DataManager from '../../utils/DataManager.js'
import warnIcon from '../../image/ic_warn.png'

import addImage from '../../image/ic_add_image.png'
import arrowImage from '../../image/ic_arrow_right.png'
import {base_url} from "../../network/config";

let isCommitEnable = true;

export default class shopInfoPost extends Component {
  config = {
    navigationBarTitleText: '发布商家信息'
  }

  constructor(props) {
    super(props)
    this.state = {
      images: [],
      localImageList:[],
      content: '',
      title: '',
      mobile: '',
      isBusiness: '',
      protocolShow: false,agree:true,
      topPriceList:[],
      chosenTop:'暂未置顶',
      chosenTopValue:'',
      chosenTopCode:'',
      payWay:0, //   0微信支付  1积分支付
      integral:'',
      contactName:'', // 联系人
    }
  }

  onPullDownRefresh(){
    Taro.stopPullDownRefresh();
  }

  componentWillMount(){
    this.categoryId = this.$router.params.categoryId;
    console.log('categoryId--------------' + this.categoryId);
  }

  componentDidMount(){

    this.auth = DataManager.getAuthInfo();
    let images = [];
    images.push(addImage);
    this.setState({
      localImageList:images ,
      isBusiness:DataManager.getIsBusiness(),
      mobile:DataManager.getBusinessMobile(),
    })
    this.loadTopList()
  }

  componentDidShow(){
    this.loadUserDetail();
    this.setState({
      isBusiness:DataManager.getIsBusiness(),
    })
  }

  loadUserDetail(){
    let _this = this;

    let url = base_url + 'rest/user/userDetail'
    Taro.request({
      url:url,
      data: {
        token:DataManager.getToken(),
        platform:'android_c',
        weixinId:DataManager.getWeiXinId(),
        loginChannel:'c',
        appId:'KC876D98B30UA40CJSNHI689FB33SDW',
        digest : 'dda484557c12febe48139d8f44051c13',
      },
      method: 'GET',
      success(res) {
        console.log('userDetail=========' + JSON.stringify(res))
        if (res.data && res.data.data){
          _this.setState({
            integral : res.data.data.integral
          })
        }
      }
    })
  }

  loadTopList(){
    let _this = this;
    let url = base_url + 'stateless/dict/dictList'
    Taro.request({
      url:url,
      data: {
        token:DataManager.getToken(),
        platform:'android_c',
        weixinId:DataManager.getWeiXinId(),
        loginChannel:'c',
        appId:'KC876D98B30UA40CJSNHI689FB33SDW',
        digest : 'dda484557c12febe48139d8f44051c13',
        type:'top'
      },
      method: 'GET',
      success(res) {
        console.log('top------------' + JSON.stringify(res))
        let topList = [];
        if (res.data.data){
          topList = topList.concat(res.data.data);
        }
        _this.setState({
          topPriceList:topList,
        })
      }
    })
  }

  onContentChange = (e) => {
    this.setState({
      content: e.target.value,
    })
  }

  uploadHeadImage(params) {

    let baseParams = { platform: 'android_c', loginChannel: 'c' };
    Object.assign(params, baseParams,this.auth);
    params.success = (res) => {
      const d = JSON.parse(res.data)
      if (d.status == 'success') {
        let list = this.state.images
        let llist = this.state.localImageList
        list.push(d.data[0])
        llist.unshift(params.filePath)
        this.setState({images: list,localImageList: llist})
      }
    }

    params.fail = (obj) => {
      console.log(obj)
    }

    Taro.uploadFile(params);
  }

  onImageClick = (item) => {
    let _this = this;
    let currentImageList = this.state.localImageList;
    if (item == addImage) {
      Taro.chooseImage({
        sourceType: ['album', 'camera'],
        sizeType:['compressed'],
        count: 10 - _this.state.localImageList.length,
        success(res) {
          // tempFilePath可以作为img标签的src属性显示图片

          let tempFilePaths = res.tempFilePaths
          tempFilePaths = tempFilePaths.concat(currentImageList);
          if (tempFilePaths.length == 10) {
            tempFilePaths.pop()
            return;
          }

          for (let i = 0 ; i < res.tempFilePaths.length ; i++){
            let tempFilePath = res.tempFilePaths[i]
            let params = {
              filePath: tempFilePath,
              name: 'imageName',
              url: 'https://www.vpin.top/a/stateless/image/fileUpload'
            }
            _this.uploadHeadImage(params)
          }
        }
      })
    }
  }

  onTitleChange = (title) => {
    this.setState({
      title: title
    })
  }

  onMobileChange = (mobile) => {
    this.setState({
      mobile: mobile
    })
  }

  onContactChange = (contact) => {
    this.setState({
      contactName: contact
    })
  }

  goToShopRegister = () => {
    Taro.navigateTo({
      url : '/pages/me/shopRegister'
    })
  }

  onSubmit() {
    if (!isCommitEnable){
      return;
    }

    if (!this.state.title){
      Taro.showToast({
        title:'请填写活动标题',
        icon:'none'
      })
      return;
    }
    if (!this.state.content){
      Taro.showToast({
        title:'请填写活动内容',
        icon:'none'
      })
      return;
    }
    isCommitEnable = false;

    if (this.state.chosenTopValue && this.state.payWay == 0){ // 先微信支付
      this.onPayForPost();
    } else {
      this.onShopInfoPost();
    }
  }

  onPayForPost(){
    let _this = this;
    Taro.request({
      url:base_url + 'rest/order/createOrder',
      data:{
        token:DataManager.getToken(),
        platform:'android_c',
        weixinId:DataManager.getWeiXinId(),
        loginChannel:'wechat',
        appId:'KC876D98B30UA40CJSNHI689FB33SDW',
        digest : 'dda484557c12febe48139d8f44051c13',
        openId:DataManager.getOpenId(),
        amount:this.state.chosenTopValue,
      },
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      method: 'POST',
      success: (obj) => {
        if (obj.data.status == 'success') {
          if (obj.data.data){
            let timeStamp = obj.data.data.timeStamp;
            let nonceStr = obj.data.data.nonceStr;
            let payPackage = obj.data.data.package;
            let signType = obj.data.data.signType;
            let paySign = obj.data.data.paySign;

            Taro.requestPayment({
              'timeStamp': timeStamp,
              'nonceStr': nonceStr,
              'package': payPackage,
              'signType': signType,
              'paySign': paySign,
              success(res){
                _this.onShopInfoPost();
              },
              fail(res){
                Taro.showToast({
                  title:'支付失败',
                  icon:'none'
                })
                console.log('pay--failed----' + JSON.stringify(res))
                isCommitEnable = true;
              }
            })
          }
        } else {
          Taro.showToast({
            title: obj.data.message,
            icon: 'none',
            duration: 1000
          })
          isCommitEnable = true;
        }
      },
      fail(obj){
        Taro.showToast({
          title: '支付失败',
          icon: 'none',
          duration: 1000
        })
        isCommitEnable = true;
      }
    })
  }

  onShopInfoPost(){
    let code = this.state.chosenTopCode;
    let data = {
      platform: 'android_c',
      loginChannel: 'c' ,
      code: code ,
      payType: this.state.payWay ,
      categoryId: this.categoryId,
      content:this.state.content,
      images:this.state.images,
      mobile:this.state.mobile,
      userName:this.state.contactName,
    };
    Object.assign(data, this.auth)

    Taro.request({
      url: 'https://www.vpin.top/a/rest/category/news/saveCategoryNews',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      dataType: 'json',
      data: data,
      success: (obj) => {
        if (obj.data.status == 'success') {
          Taro.showToast({
            title: '发布成功',
            icon: 'success',
            duration: 1000
          });
          Taro.eventCenter.trigger('shopInfoPost' ,[]);
          Taro.navigateBack({delta: 1});
        } else {
          Taro.showToast({
            title: '发布失败',
            icon: 'none',
            duration: 1000
          })
        }
        isCommitEnable = true;
      },
      fail(obj){
        Taro.showToast({
          title: '程序异常',
          icon: 'none',
          duration: 1000
        })
        isCommitEnable = true;
      }
    })
  }

  onHandleDeleteImage(index){

    let _images = this.state.images.filter( (ele, _index)=> _index != index )
    let _localImages = this.state.localImageList.filter( (ele, _index)=> _index != index )
    this.setState({
       images: _images ,
       localImageList:_localImages,
     })
  }

  onHandleAgree(){

    const agree = this.state.agree
    this.setState({agree:!agree})

  }

  handleShowProtocol() {
    Taro.navigateTo({
      url:'/pages/protocol/shopInfoProtocol'
    });
  }

  onTopSelect = (e) => {

    if (this.state.integral < this.state.topPriceList[e.detail.value].value) {
      this.setState({
        chosenTop: this.state.topPriceList[e.detail.value].name,
        chosenTopValue:this.state.topPriceList[e.detail.value].value,
        chosenTopCode:this.state.topPriceList[e.detail.value].code,
        payWay:0
      })
    } else {
      this.setState({
        chosenTop: this.state.topPriceList[e.detail.value].name,
        chosenTopValue:this.state.topPriceList[e.detail.value].value,
        chosenTopCode:this.state.topPriceList[e.detail.value].code
      })
    }
  }

  onTopCancel = () =>{
    this.setState({
      chosenTop: '暂未置顶',
      chosenTopValue:'',
      chosenTopCode:''
    })
  }

  handlePayWayChange = (value) =>{
    this.setState({
      payWay:value,
    })
  }

  render() {
    let imageConatiner = this.state.localImageList.map( (item , index) => {
      let imageItemClass =  item == addImage? 'image-item-s' :  'image-item';
      return <View style='position:relative;'><View className={imageItemClass} onClick={this.onHandleDeleteImage.bind(this, index)}>X</View><Image src={item} className='shop-post-single-image' mode='aspectFill' onClick={this.onImageClick.bind(this, item)} /></View>
    })

    let postZoneClass = (this.state.isBusiness==1) ? 'display:block' : 'display:none';

    let commitValue = '提交'
    if (this.state.chosenTopValue){
      if (this.state.payWay == 0) {
        commitValue= '需支付 ¥ ' + this.state.chosenTopValue + '元';
      } else if (this.state.payWay == 1){
        commitValue= '需支付 ' + this.state.chosenTopValue * 10 + '积分';
      }
    }

    let weiPay = {label: '微信支付', value: 0};
    let scoreLabel = '积分支付' + ' （剩余积分：' + this.state.integral + '）'
    let scoreDisable = this.state.integral < this.state.chosenTopValue * 10;
    let scorePay = {label:scoreLabel , value: 1 , disabled : scoreDisable};

    let payWayList = [weiPay , scorePay];

    return (
      <View className='shop-post-container'>
        <View className='shop-post-container-sub'>
          {this.state.isBusiness == 0 ?
            <View className='post-not-business-container' onClick={this.goToShopRegister.bind(this)}>
              <Image className='job-post-warn-icon' src={warnIcon}></Image>
              <Text className='post-commit'>成为商家后才可发布招聘信息，去成为商家 >></Text>
            </View> : null
          }
          <AtNoticebar>
            免责声明：本平台不对任何人提供任何形式的担保，所有法律信息仅供参考，不承担由此产生的任何民事及法 律责任。用户使用本平台即视为同意。
          </AtNoticebar>

          <View className='info-form'>
            <AtInput
              className='shop-post-input'
              name='infoTitle'
              value={this.state.title}
              clear
              title='活动标题'
              type='text'
              placeholder='请填写活动标题'
              border
              maxlength={50}
              onChange={this.onTitleChange.bind(this)}
            />
            <AtInput
              className='shop-post-input'
              name='infoMobile'
              value={this.state.mobile}
              clear
              title='联系方式'
              type='digit'
              placeholder='请填写联系方式'
              border
              maxlength={50}
              onChange={this.onMobileChange.bind(this)}
            />
            <AtInput
              className='shop-post-input'
              name='infoContact'
              value={this.state.contactName}
              clear
              title='联系人'
              type='text'
              placeholder='请填写联系人'
              border
              maxlength={50}
              onChange={this.onContactChange.bind(this)}
            />
            <AtTextarea
              className='shop-post-multi-input'
              height='400px'
              value={this.state.content}
              maxlength='1000'
              placeholder='请填写内容'
              onChange={this.onContentChange.bind(this)}
            />
          </View>
          <View className='shop-post-divider'></View>

          <Picker
            mode='selector'
            range={this.state.topPriceList}
            rangeKey='name'
            value='0'
            onChange={this.onTopSelect.bind(this)}
            onCancel={this.onTopCancel.bind(this)}
          >
            <View className='shop-post-top-container'>
              <Text className='shop-post-top-text'>是否置顶</Text>
              <View className='shop-post-top-right'>
                <Text className='shop-post-top-text'>{this.state.chosenTop}</Text>
                <Image className='shop-post-top-arrow' src={arrowImage}/>
              </View>
            </View>
          </Picker>

          {this.state.chosenTopValue && <AtRadio
            options={payWayList}
            value={this.state.payWay}
            onClick={this.handlePayWayChange.bind(this)}
            style='color:#666666;font-size:12px'
          />}

          <View style={postZoneClass}>
            <View className='shop-post-divider'></View>
            <View className='shop-post-image-container'>
              {imageConatiner}
            </View>

            <View className='disclaimer'>
              <CustomRadio checked={this.state.agree} onClick={this.onHandleAgree.bind(this)}/>
              <View className='protocol-ele' onClick={this.handleShowProtocol.bind(this)}>我已阅读并同意《商家活动发布协议》</View>
            </View>

            <View className='post-section' onClick={this.onSubmit.bind(this)}>
              <Button disabled={!this.state.agree} className='shop-post-commit'>{commitValue}</Button>
            </View>
          </View>

        </View>

      </View>
    )
  }


}
